package pdf;

import com.alibaba.excel.EasyExcel;
import excel.ExcelDto;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yun lang
 * @version 1.0
 * @description: 解析对应的  E20230001180610677
 * @date 2024/12/10 17:58
 */
public class Pdf1 {
    public static void main(String[] args) {
        /*String filePath = "/Users/liangpei/Documents/pdf/（已压缩）报关单202401.pdf";
        parse(new File(filePath), "/Users/liangpei/Documents/pdf/");*/

        // 获取 JAR 文件所在目录
        //String jarPath = new File(PdfTest.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent();
        File pdfDirectory = new File("E:\\pdf");
        // 获取目录下的所有PDF文件
        File[] pdfFiles = pdfDirectory.listFiles((dir, name) -> name.toLowerCase().endsWith(".pdf"));
        if (pdfFiles != null) {
            for (File file : pdfFiles) {
                System.out.println("正在处理文件: " + file.getName());
                parseTxt(file, "E:\\pdf");
                //parsePic(file, "/Users/liangpei/Documents/pdf/");
            }
        } else {
            System.out.println("没有找到 PDF 文件。");
        }
        System.out.println("处理完成。");
    }
    /*public static void main(String[] args) {
        String filePath = "/Users/liangpei/Documents/pdf/（已压缩）报关单202401.pdf";
        parse(new File(filePath), "/Users/liangpei/Documents/pdf/");
    }*/

    public static void parseTxt(File file, String jarPath) {
        //File file = new File(filePath);
        try (PDDocument document = Loader.loadPDF(file)) {
            //获取总页数
            int pageCount = document.getNumberOfPages();
            System.out.println("PDF 总页数：" + pageCount);

            List<ExcelDto> excelDtoList = new ArrayList<ExcelDto>();

            //循环读取
            for (int i = 1; i <= pageCount; i++) {
                //获取指定页
                PDFTextStripper stripper = new PDFTextStripper();
                stripper.setStartPage(i);
                stripper.setEndPage(i);
                String text = stripper.getText(document);

                // 提取第一行数据
                Pattern firstLinePattern = Pattern.compile("\\*(\\d+)\\*");

                String firstLineData = "";
                Matcher firstLineMatcher = firstLinePattern.matcher(text);
                if (firstLineMatcher.find()) {
                    firstLineData = firstLineMatcher.group(1);
                    System.out.println("报关单编号: " + firstLineData);
                }

                if("223120230004544084".equals(firstLineData)){
                    System.out.println(1);
                }


                // 提取商品编码和商品名称
                Pattern productInfoPattern = Pattern.compile("([1-9])\\s(\\d{10})(.+)");
                Matcher productInfoMatcher = productInfoPattern.matcher(text);

                // 提取金额和货币
                Pattern amountCurrencyPattern = Pattern.compile("(\\d+\\.\\d+)\\s*(美元|人民币)");
                Matcher amountCurrencyMatcher = amountCurrencyPattern.matcher(text);

                ExcelDto excelDto = new ExcelDto();
                excelDto.setNo(firstLineData);
                while (amountCurrencyMatcher.find()) {
                    String amount = amountCurrencyMatcher.group(1);
                    String currency = amountCurrencyMatcher.group(2);
                    System.out.println("金额: " + amount);
                    System.out.println("货币: " + currency);
                    excelDto.setAmount(amount);
                    excelDto.setType(currency);
                }

                while (productInfoMatcher.find()) {
                    String itemNumber = productInfoMatcher.group(1);
                    String customsNumber = productInfoMatcher.group(2);
                    String productName = productInfoMatcher.group(3).trim();
                    System.out.println("项目编号: " + itemNumber);
                    System.out.println("商品编码: " + customsNumber);
                    System.out.println("商品名称: " + productName);
                    excelDto.setGoodsNo(customsNumber);
                }

                excelDtoList.add(excelDto);
            }
            String fileName = file.getName().replace(".pdf", ".xlsx");


            String excelPath = jarPath + File.separator + "excel" + File.separator + fileName;
            System.out.println("正在生成 Excel 文件: " + excelPath);
            // 确保目标目录存在
            File excelDir = new File(jarPath + File.separator + "excel");
            if (!excelDir.exists()) {
                boolean mkdirsSuccess = excelDir.mkdirs();
                if (mkdirsSuccess) {
                    //System.out.println("目录创建成功: " + excelDir.getAbsolutePath());
                } else {
                    //System.err.println("目录创建失败: " + excelDir.getAbsolutePath());
                    return;
                }
            }


            EasyExcel.write(new File(excelPath), ExcelDto.class)
                    //.registerWriteHandler(new CustomMergeStrategy(0))
                    .sheet("报关单")
                    .doWrite(excelDtoList);
        } catch (Exception e) {
            System.out.println("处理文件 " + file.getName() + " 出错。");
            e.printStackTrace();
        }
    }
}
